package top.doe.rpc.system_a.advance;

import top.deo.rpc.base.common.OrderInfoQuerierInterface;
import top.deo.rpc.base.common.Request;
import top.deo.rpc.base.common.Response;
import top.deo.rpc.base.common.UserInfoQuerierInterface;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

public class MainTest {
    public static void main(String[] args) {

        // system_b. OrderInfoQuerier.getOrderAmount(int orderId)

        OrderInfoQuerierInterface orderInfoQuerier = (OrderInfoQuerierInterface) getProxyInstance(OrderInfoQuerierInterface.class);
        String userName = orderInfoQuerier.getOrderUser(100);
        System.out.println(userName);


        UserInfoQuerierInterface userInfoQuerier = (UserInfoQuerierInterface) getProxyInstance(UserInfoQuerierInterface.class);
        String userName1 = userInfoQuerier.getUserName(1);
        System.out.println(userName1);

        int userAge = userInfoQuerier.getUserAge(100);
        System.out.println(userAge);



    }


    private static Object getProxyInstance(Class<?> interfaceCls) {
        return Proxy.newProxyInstance(
                MainTest.class.getClassLoader(),
                new Class[]{interfaceCls}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        Socket socket = new Socket("localhost", 9099);

                        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
                        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

                        // 发起请求
                        Request request = new Request(method.getDeclaringClass().getName(), method.getName(), method.getParameterTypes(), args);

                        out.writeObject(request);
                        out.flush();


                        // 接收响应
                        Response response = (Response) in.readObject();
                        Object result = response.getResult();

                        in.close();
                        out.close();
                        socket.close();

                        return result;
                    }
                });
    }

}
